package com.radioapp.liaoliaobao.module.user.material;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.jaydenxiao.common.base.BaseActivity;
import com.jaydenxiao.common.base.BaseRiggerFragment;
import com.jaydenxiao.common.commonutils.JsonUtils;
import com.jaydenxiao.common.commonutils.ToastUitl;
import com.jaydenxiao.common.url.BaseConstant;
import com.jkb.fragment.rigger.rigger.Rigger;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.radioapp.liaoliaobao.R;
import com.radioapp.liaoliaobao.app.GlideApp;
import com.radioapp.liaoliaobao.app.GlideImageLoader;
import com.radioapp.liaoliaobao.bean.ExpectBean;
import com.radioapp.liaoliaobao.bean.appointment.CareerSBean;
import com.radioapp.liaoliaobao.bean.appointment.DatingHopesBean;
import com.radioapp.liaoliaobao.bean.user.UserBean;
import com.radioapp.liaoliaobao.constant.Constants;
import com.radioapp.liaoliaobao.constant.Global;
import com.radioapp.liaoliaobao.constant.IntentConstant;
import com.radioapp.liaoliaobao.module.lifecyclerObserver.RxPermissionsFragmentObserver;
import com.radioapp.liaoliaobao.uihelper.UiHelper;
import com.radioapp.liaoliaobao.utils.AssetsUtils;
import com.radioapp.liaoliaobao.utils.timePicker.SelectImageUtils;
import com.radioapp.liaoliaobao.utils.timePicker.TimePickerCareerUtil;
import com.radioapp.liaoliaobao.utils.timePicker.TimePickerCityUtil;
import com.radioapp.liaoliaobao.utils.timePicker.TimePickerDateUtil;
import com.radioapp.liaoliaobao.view.dialog.more_select.MoreSelectDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 功能：填写资料
 * 描述
 * Created by yue on 2019-07-16
 */
public class MaterialFragment extends BaseRiggerFragment<MaterialView, MaterialPresenter> implements MaterialView,
        RxPermissionsFragmentObserver.PermissionCallBack, BaseActivity.ActivityResultByFragment {
    @BindView(R.id.iv_image)
    ImageView ivImage;  //图片
    @BindView(R.id.et_nickName)
    EditText etNickName;  //昵称
    @BindView(R.id.tv_age)
    TextView tvAge;  //年纪
    @BindView(R.id.tv_job)
    TextView tvJob; //职业
    @BindView(R.id.tv_address)
    TextView tvAddress; //地址
    @BindView(R.id.tv_range)
    TextView tvRange;//约会范围
    @BindView(R.id.tv_show)
    TextView tvShow; //约会节目
    @BindView(R.id.tv_expect)
    TextView tvExpect; //约会期望
    @BindView(R.id.et_wx)
    EditText etWx; //wx
    @BindView(R.id.et_qq)
    EditText etQQ; //qq
    @BindView(R.id.et_height)
    EditText etHeight; //身高
    @BindView(R.id.et_weight)
    EditText etWeight; //体重
    @BindView(R.id.et_self)
    EditText etSelf; //用一句话介绍自己
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    private int gender = 1;

    private List<LocalMedia> selectList = new ArrayList<>();
    private List<DatingHopesBean> datingHopesBeans;
    //本地的数据
    List<ExpectBean> expectBeans;

    private TimePickerCityUtil timePickerCityUtil;
    private TimePickerCareerUtil timePickerCareerUtil;
    private TimePickerDateUtil timePickerDateUtil;
    private RxPermissionsFragmentObserver rxPermissionsObserver;

    private String dating_types; //约会节目
    private String dating_hopes;//约会期望
    private String user_regions;//约会范围
    private int career_id = -1; //职业id
    private Integer province_id;
    private Integer city_id;
    private String imageUrl = "";//图片地址


    @Override
    protected int getLayoutResource() {
        return R.layout.activity_material;
    }

    @Override
    public void initView() {

        initToolbar("填写资料", true, false, null);

        ((BaseActivity) mActivity).setActivityResultByFragment(this);

        //权限
        rxPermissionsObserver = new RxPermissionsFragmentObserver(this);
        getLifecycle().addObserver(rxPermissionsObserver);
        rxPermissionsObserver.setCallBack(this);
        setData();
        //获取期望约会列表
        // mPresenter.getDatingHopes();
        expectBeans = AssetsUtils.newInterface().expectBeans;
    }

    @Override
    public void tokenInvalidRefresh() {
    }

    @Override
    public void handIntent(Bundle bundle) {
        gender = bundle.getInt(IntentConstant.GENDER, 0);

    }

    /**
     * 编辑资料的设置数
     */
    void setData() {
        UserBean userBean = Global.getUserInfo();

        //当用户当值不为空情况
        if (userBean.getGender() != 0) {
            try {
                toolbar_header.setText("修改资料");
                if(gender==0){
                    gender = userBean.getGender() == 0 ? 1 : userBean.getGender();
                }else{
                    gender=userBean.getGender();
                }
                etNickName.setText(userBean.getNickname());
                tvAge.setText(userBean.getBirth_at().substring(0, 10));
                career_id = userBean.getCareer_id();
                province_id = userBean.getProvince_id();
                city_id = userBean.getCity_id();
                tvJob.setText(String.valueOf(AssetsUtils.newInterface().getCareersId(userBean.getCareer_id()).get("careerName")));
                ArrayMap<String, Object> address = AssetsUtils.newInterface().getAddress(userBean.getProvince_id(), userBean.getCity_id(), -1);
                String provinceName = address.get("provinceName") == null ? "" : address.get("provinceName") + "";
                String cityName = address.get("cityName") == null ? "" : address.get("cityName") + "";
                tvAddress.setText(provinceName +
                        "-" + cityName);
                //约会范围
                List<UserBean.RegionsBean> regionsBeans = userBean.getRegions();
                if (regionsBeans != null && regionsBeans.size() > 0) {
                    StringBuffer rangeBuffer = new StringBuffer();
                    StringBuffer rangeBufferId = new StringBuffer();
                    for (UserBean.RegionsBean bean : regionsBeans) {
                        rangeBufferId.append(bean.getProvince_id()).append("-").append(bean.getCity_id());
                        ArrayMap<String, Object> address1 = AssetsUtils.newInterface().getAddress(bean.getProvince_id(), bean.getCity_id(), -1);
                        rangeBuffer.append(address1.get("provinceName") + "-" + address1.get("cityName") + ",");

                    }
                    if (!TextUtils.isEmpty(rangeBuffer))
                        tvRange.setText(rangeBuffer.substring(0, rangeBuffer.length() - 1));
                    user_regions = rangeBufferId.toString();
                }
                //节目
                List<UserBean.UserDatingTypesBean> datingTypesBeans = userBean.getUser_dating_types();
                if (datingTypesBeans != null && datingTypesBeans.size() > 0) {
                    StringBuffer typeBuffer = new StringBuffer();
                    StringBuffer typeBufferId = new StringBuffer();
                    for (UserBean.UserDatingTypesBean typesBean : datingTypesBeans) {
                        typeBufferId.append(typesBean.getDating_type_id()).append(",");
                        typeBuffer.append(AssetsUtils.newInterface().getProgramBeansName(typesBean.getDating_type_id()).get("name")).append(",");
                    }
                    if (!TextUtils.isEmpty(typeBuffer)) {
                        tvShow.setText(typeBuffer.substring(0, typeBuffer.length() - 1));
                        dating_types = typeBufferId.substring(0, typeBufferId.length() - 1);
                    }

                }
                //期望
                List<UserBean.UserDatingHopesBean> user_dating_hopes = userBean.getUser_dating_hopes();
                if (user_dating_hopes != null && user_dating_hopes.size() > 0) {
                    StringBuffer typeBuffer = new StringBuffer();
                    StringBuffer typeBufferId = new StringBuffer();
                    for (UserBean.UserDatingHopesBean typesBean : user_dating_hopes) {
                        typeBufferId.append(typesBean.getDating_hope_id()).append(",");
                        typeBuffer.append(AssetsUtils.newInterface().getExpectName(typesBean.getDating_hope_id()).get("name")).append(",");
                    }
                    if (!TextUtils.isEmpty(typeBuffer)) {
                        tvExpect.setText(typeBuffer.substring(0, typeBuffer.length() - 1));
                        dating_hopes = typeBufferId.substring(0, typeBufferId.length() - 1);
                    }

                }
                etWx.setText(userBean.getWechat());
                etQQ.setText(userBean.getQq());
                etHeight.setText(userBean.getHeight());
                etWeight.setText(userBean.getWeight());
                etSelf.setText(userBean.getIntro());
                GlideImageLoader.displayImage(mActivity, BaseConstant.IMAGEURL + userBean.getAvatar(), ivImage);
                imageUrl = BaseConstant.IMAGEURL + userBean.getAvatar();

            } catch (Exception e) {
                e.printStackTrace();
            }


        }


        tvCommit.setText(gender==1?"申请邀请码":"完成");
    }


    @SuppressLint("SetTextI18n")
    @OnClick({R.id.rl_image, R.id.ll_age, R.id.ll_job, R.id.ll_address, R.id.ll_range, R.id.ll_expect, R.id.ll_show, R.id.tv_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_image: //选择图片
                rxPermissionsObserver.requestPermissions(1, Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA);
                break;
            case R.id.ll_age: //选择年龄
                timePickerDateUtil = TimePickerDateUtil.newInterface();
                timePickerDateUtil.showTimePicker(mActivity, "选择生日", new TimePickerDateUtil.DateSelectListener() {
                    @Override
                    public void onSelected(String date) {
                        tvAge.setText(date);

                    }
                });

                break;
            case R.id.ll_job: //选择职业
                timePickerCareerUtil = TimePickerCareerUtil.newInterface();
                timePickerCareerUtil.showPickerView(mActivity, 2, new TimePickerCareerUtil.CitySelectListener() {
                    @Override
                    public void onSelected(CareerSBean careerSBean, CareerSBean.CarBean carBean) {
                        tvJob.setText(carBean.getName());
                        career_id = carBean.getId();
                    }
                });
                break;
            case R.id.ll_address: //地址
                timePickerCityUtil = TimePickerCityUtil.newInterface();
                timePickerCityUtil.showPickerView(mActivity, 2, (province, citysBean, areasBean) -> {
                    tvAddress.setText(province.getAreaName() + citysBean.getAreaName());
                    province_id = province.getId();
                    city_id = citysBean.getId();
                });
                break;
            case R.id.ll_range: //约会范围
                timePickerCityUtil = TimePickerCityUtil.newInterface();
                timePickerCityUtil.showPickerView(mActivity, 2, (province, citysBean, areasBean) -> {
                    tvRange.setText(province.getAreaName() + citysBean.getAreaName());
                    user_regions = province.getId() + "-" + citysBean.getId();
                });
                break;
            case R.id.ll_expect: //约会期望
                if (datingHopesBeans != null) {
                    MoreSelectDialog.newInstance(datingHopesBeans, new MoreSelectConfirmClick()).
                            setMaxSelect(3).setTitle("约会期望").show(getChildFragmentManager(), "dialog");

                } else {
                    MoreSelectDialog.newInstance(expectBeans, new MoreSelectConfirmClick1()).
                            setMaxSelect(3).setTitle("约会期望").show(getChildFragmentManager(), "dialog");
                }
                break;

            case R.id.ll_show: //约会节目
                MoreSelectDialog.newInstance(Constants.getShowList(), new MoreSelectShowConfirmClick()).
                        setMaxSelect(3).setTitle("约会节目").show(getChildFragmentManager(), "showDialog");

                break;
            case R.id.tv_commit: //提交
                if (mPresenter.isFlag(etNickName.getText().toString(), career_id, tvAge.getText().toString(),
                        dating_types, dating_hopes, user_regions, province_id, city_id, etWx.getText().toString(), etQQ.getText().toString())) {
                    if (selectList.size() == 0 && TextUtils.isEmpty(imageUrl)) {
                        ToastUitl.showLong("请上传头像");
                        return;
                    }
                    if (TextUtils.isEmpty(imageUrl)) {
                        mPresenter.uploadAcatar(new File(getpathImage(selectList.get(0))));
                    }else{
                        mPresenter.updateInfo(
                                mPresenter.setParams(gender, etNickName.getText().toString(), tvAge.getText().toString(), career_id,
                                        dating_types, dating_hopes, user_regions, province_id, city_id, etWx.getText().toString(), etQQ.getText().toString(),
                                        etHeight.getText().toString(), etWeight.getText().toString(), etSelf.getText().toString()));
                    }

                }
                break;
        }
    }


    /**
     * 多选的接口回掉，约会期望
     */
    class MoreSelectConfirmClick implements MoreSelectDialog.OnConfirmClickListener<DatingHopesBean> {

        public void onClick(Set<DatingHopesBean> selectLists) {
            StringBuffer stringBuffer = new StringBuffer();
            StringBuffer stringhopes = new StringBuffer();
            String text = "";
            if (selectLists != null && selectLists.size() > 0) {
                for (DatingHopesBean list : selectLists) {
                    stringBuffer.append(list.getName()).append(",");
                    stringhopes.append(list.getId()).append(",");
                }
                if (stringBuffer.length() > 0) {
                    text = stringBuffer.substring(0, stringBuffer.length() - 1);
                    dating_hopes = stringhopes.substring(0, stringhopes.length() - 1);
                }
                tvExpect.setText(text);
            }

        }
    }

    /**
     * 多选的接口回掉，约会期望(本地)
     */
    class MoreSelectConfirmClick1 implements MoreSelectDialog.OnConfirmClickListener<ExpectBean> {

        public void onClick(Set<ExpectBean> selectLists) {
            StringBuffer stringBuffer = new StringBuffer();
            StringBuffer stringhopes = new StringBuffer();
            String text = "";
            if (selectLists != null && selectLists.size() > 0) {
                for (ExpectBean list : selectLists) {
                    stringBuffer.append(list.getName()).append(",");
                    stringhopes.append(list.getId()).append(",");
                }
                if (stringBuffer.length() > 0) {
                    text = stringBuffer.substring(0, stringBuffer.length() - 1);
                    dating_hopes = stringhopes.substring(0, stringhopes.length() - 1);
                }
                tvExpect.setText(text);
            }

        }
    }

    /**
     * 多选的接口回掉，约会节目
     */
    class MoreSelectShowConfirmClick implements MoreSelectDialog.OnConfirmClickListener<DatingHopesBean> {

        public void onClick(Set<DatingHopesBean> selectLists) {
            StringBuffer stringBuffer = new StringBuffer();
            StringBuffer stringShow = new StringBuffer();
            String text = "";
            if (selectLists != null && selectLists.size() > 0) {
                for (DatingHopesBean list : selectLists) {
                    stringBuffer.append(list.getName()).append(",");
                    stringShow.append(list.getId()).append(",");
                }
                if (stringBuffer.length() > 0) {
                    text = stringBuffer.substring(0, stringBuffer.length() - 1);
                    dating_types = stringShow.substring(0, stringShow.length() - 1);
                }
                tvShow.setText(text);
            }

        }
    }

    @Override
    public void success() {
        ToastUitl.showLong("提交成功");
        if(Global.getUserInfo().getId()==0){
           if(gender==1){
               UiHelper.showCodeFragment(mActivity);
               return;
           }
        }
        UiHelper.showMainFragment(mActivity);
    }

    @Override
    public void avatarUrl(String avatar_url) {
        // ToastUitl.showLong("上传头像成功");
        mPresenter.updateInfo(
                mPresenter.setParams(gender, etNickName.getText().toString(), tvAge.getText().toString(), career_id,
                        dating_types, dating_hopes, user_regions, province_id, city_id, etWx.getText().toString(), etQQ.getText().toString(),
                        etHeight.getText().toString(), etWeight.getText().toString(), etSelf.getText().toString()));
    }

    @Override
    public void getDatingHopes(List<DatingHopesBean> datingHopesBeans) {
        this.datingHopesBeans = datingHopesBeans;
    }


    @Override
    public void onActivityResultByFragment(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择
                    selectList = PictureSelector.obtainMultipleResult(data);
                    if (selectList.get(0) != null)
                        GlideApp.with(mContext).load(getpathImage(selectList.get(0))).into(ivImage);
                    break;
            }
        }
    }


    /**
     * 获取图片，
     *
     * @param model
     * @return
     */
    public String getpathImage(LocalMedia model) {
        String path = "";
        if (model.isCut() && !model.isCompressed()) {
            // 裁剪过
            path = model.getCutPath();
        } else if (model.isCompressed() || (model.isCut() && model.isCompressed())) {
            // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
            path = model.getCompressPath();
        } else {
            // 原图
            path = model.getPath();
        }
        return path;
    }


    /**
     * 用户同意了权限
     *
     * @param type :区别不同的初始化
     */
    @Override
    public void granted(int type) {
        SelectImageUtils.showALlImage(mActivity, selectList, 1, PictureConfig.CHOOSE_REQUEST);
    }

    /**
     * 用户拒绝了权限
     */
    @Override
    public void shouldShowRequestPermissionRationale() {

    }

    /**
     * 用户勾选了不再提醒
     */
    @Override
    public void other() {

    }


}
